import { Component, OnInit, Injector, Output, EventEmitter, Input, ElementRef, ViewChild } from '@angular/core';
import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../public/serve/hints/hints.service';
import { RemoveTableService } from '../../../public/serve/remove-table/remove-table.service';
import { InitService } from '../../../public/serve/init/init.service';
import { BaseTreeComponent } from '../../../public/components/base-tree/base-tree.component';
import { HttpClient } from '@angular/common/http';
import { TreeNode } from '../../../public/common/api';
import { tokenName } from '@angular/compiler';
import { ActivatedRoute,Params } from '@angular/router';
import { internal } from '../../internal.data';
import { Observable } from 'rxjs/Rx';
import {keyword} from '../../../keyword/keyword.data';

declare var $:any;
@Component({
  selector: 'app-view-keyword',
  templateUrl: './view-keyword.component.html',
  styleUrls: ['./view-keyword.component.css']
})
export class ViewKeywordComponent implements OnInit {

  pageNo :number = 1;
  pageSize      : number = 20;
  total: number = 0;
  naturalNum: number = 0;
  totalRecords: number;
  @Output() onSubmitAppView = new EventEmitter<void>();
  public productTypeCurrentId : any;
  @Input() showTitle: any;
  treeData      : TreeNode[];
  selectedData  : TreeNode[];
  listData      = [];
  loading: boolean = false;
  @Input() searchData: any;
  currentThemeWordInfo:any;
  tableData = {};
  taskType: any;
  isSelectAll : boolean = false;
  isChose : boolean = false;

  themeTableName:any;

  arrTid = [];

  public getCheckedTableId = [];

  @Input() internalParam : any;
  
  paramData = {};

  @ViewChild("scrollMe") myScrollContainer;

  result = [];
  treeDataScroll = [];
  previousActive : boolean = false;//上一页
  nextActive : boolean = false;//下一页
  totalPage :number;

  public internalThemeWordsTablesRelEmit: any;
  public internalThemeWordsLeftEmit: any;
  
  constructor(
    private server: Service,
    public request: CudTableService,
    private tableListService: CudTableService,
    private hintsService: HintsService,
    private removeTableService: RemoveTableService,
    public initService: InitService,
    private http: HttpClient,
    private activatedRoute: ActivatedRoute,
  ) { }

  ngOnInit() {   
    this.activatedRoute.queryParams.subscribe((p: Params) => {
      this.taskType = p['taskType'];
    });

    if(this.pageNo == 1){
      this.previousActive = false;
      this.nextActive = true;
    }
    if(this.taskType == 2){
      this.internalThemeWordsLeftEmit = this.server.internalThemeWordsLeftEmit.subscribe((value: any) => {
        if (value) {
          this.currentThemeWordInfo = value
        }
      });

      this.internalThemeWordsTablesRelEmit = this.server.internalThemeWordsTablesRelEmit.subscribe((value: any) => {
        this._clickButton();
      });
    }


    //滚动翻页
    // const node = document.querySelector('div[id=divTreeDataScroll]');
    // Observable.fromEvent(node,'scroll').subscribe((event)=>{
    //   //如何判断滚动条到头部了
    //   if (this.myScrollContainer.nativeElement.scrollTop == 0) {
    //     //this.onScrollUp();
    //     $('#divTreeDataScroll').animate({scrollTop:5},'slow');
    //   }

    //   //如何判断滚动条到底部了
    //   if ((this.myScrollContainer.nativeElement.scrollTop + this.myScrollContainer.nativeElement.clientHeight) == this.myScrollContainer.nativeElement.scrollHeight) {
    //     //this.onScrollDown();
    //     $('#divTreeDataScroll').animate({scrollTop:330},'slow');
    //   }

    // })
  }

  ngOnDestroy() {
    this.internalThemeWordsLeftEmit ? this.internalThemeWordsLeftEmit.unsubscribe() : '';
    this.internalThemeWordsTablesRelEmit ? this.internalThemeWordsTablesRelEmit.unsubscribe() : '';
  }

  _infoScroll(){
    this.pageNo = 1;
    this.result = [];
    this.treeDataScroll = [];
    this.treeData = [];
  }

  //下一页
  onScrollDown(){
    this.totalPage  = Math.ceil(this.total/  this.pageSize);

    if(this.pageNo < this.totalPage){
      this.pageNo += 1;
      this.previousActive = true;
      this.nextActive = true;
      this._clickButton();
    }

    if(this.pageNo == this.totalPage){
      this.previousActive = true;
      this.nextActive = false;
    }
  }

  //上一页
  onScrollUp(){
    
    if(this.pageNo > 1){
      this.pageNo -= 1;
      this.nextActive = true;
      this._clickButton();
    }
    if(this.pageNo == 1){
      this.previousActive = false;
    } 
  }

  /**
   * 点击‘查看主题词’
   */
  _clickButton(){
    if(this.internalParam){
      this.paramData = {
        "taskId":this.internalParam.taskId,
        "productId":this.internalParam.productId,
        "themeTableId":this.internalParam.themeTableId,
        "themeTableName":this.internalParam.themeTableName,
        "themeWordsId":"",
      };
      
      this.tableData = {
        token         : internal.retrieval.token,
        themeTableId  : this.paramData["themeTableId"],
        pageNo        : this.pageNo,
        pageSize      : this.pageSize,
        checkStatus   : 1,
        queryCriteria : this.searchData,
      };
      if(this.taskType == 2){
        this._getRelThemeList();
      }else{
        this._getIndexedTables(); //已标引的主题词
      }
      
    }
  }

  //验证是否有重复的选择
  _isNodeSelect(id){
    let flag = false;

    this.getCheckedTableId.forEach(str => {
      if (Number(id) === Number(str['val'])) {
        flag = true;
      }
    });

    return flag;
  }

  /**
   * 选中的节点
   * @param event 
   * @param id 
   */
  _nodeSelect(bool,event) {
    
    if(bool == true){

      if(this.getCheckedTableId.length > 0){

        let flag = this._isNodeSelect(event.id);
        if(flag){
          this.getCheckedTableId.splice(this.getCheckedTableId.findIndex(item => item['val'] === event.id), 1);
        }else{
          this.selectedData.push(event);
        }

      }else{
        this.selectedData.push(event);
      }
      
      let arr = {
        'txt':event.name,
        'val':event.id
      };
      this.getCheckedTableId.push(arr);

    }else{

      if(this.getCheckedTableId.length > 0){
        $("#checked_"+event.id).prop("checked",'');
        //删除
        this.checkNode(event.id);
      }

      this.getCheckedTableId.splice(this.getCheckedTableId.findIndex(item => item['val'] === event.id), 1);
    }
  }

  /**
   * 判断是否为空数组
   */ 
  _isEmpty() {
    if (this.getCheckedTableId.length==0) {
      return true;
    }
    return false;
  }

   /**
   * 确定标引
   */
  _addKeywordTheme(){
    if (this.getCheckedTableId.length > 0) {
      this.server.onSubmitAppViewEmit.emit(this.getCheckedTableId);
    }
  }

  /**
   * 删除
   * @param event 
   */
  _nodeUnselect(bool,event,length) {
    this.checkNode(event.id);
  }

  /**
   * 
   * 查询任务已分配的主题词表的主题词列表
   * 树状图
   */ 
  _keywordTree() {
    //this.loading = true;
    this.themeTableName =  this.paramData['themeTableName'];//当前主题词表的名称
    let data = this.tableData;
    this.request.postRequest( this.server.baseUrl + 'Service/ThemeWords/getThemeWordsList',data).then((res:any) => {
      
      if (res.result_code === '0000') {
        this.listData = res.result;
        this.treeData = this._processTreeData(this.listData,'themeWordsId','parentid','name');
        this.totalRecords = res.length;
        this.total = res.length;

        for(let i=0;i < this.treeData.length;++i){
          this.result.push(this.treeData[i]);
        }
        this.treeDataScroll = [...this.result];

         // 展开所有节点
         this._expandAll();
         this._infoTheme();
         //this.loading = false;
      }else{
        this.hintsService.messages(res.message,res.result_code);
      }
      return;
    })
    .catch((err: any)=>{
      this.hintsService.messages("error","error");
      return;
    });
  }

  /**
   * 查询已标引的主题词列表
   */
  _getIndexedTables(){
    let url = this.server.baseUrl + 'Service/IdxProduct/getProductThemeWordsList';
    let data = {
          "token": keyword.retrieval.token,
          "productId":this.paramData['productId'],
          "taskId":this.paramData['taskId'],
          "themeTableId":this.paramData['themeTableId'],
          "themeWordsId":this.paramData['themeWordsId'],
          "id":"",
          "pageNo":1,
          "pageSize":2000,
          "startTime":"",
          "endTime":"",
          "queryCriteria":""
        };
   
    this.request.postRequest(url,data).then((res:any) => {
      
        if (res.result_code === '0000') {
          let tabValList = [];
          let i=0;
          for (let item of res.result) {
            
            if(item['idxProductsThemeVo']['idxThemeWords']){
              let themeWords = item['idxProductsThemeVo']['idxThemeWords'];
              let tname = themeWords['name'];
              if(themeWords['arrparentid'] != '0'){
                tname = this._getThemeName(this.listData,themeWords['arrparentid'])+themeWords['name'];
              }

              this.arrTid[i] = themeWords['themeWordsId'];
              i++;
          
              let dataArr = {
                  id:themeWords['themeWordsId'],
                  label: themeWords['name'],
                  data: themeWords['name'],
                  createBy:themeWords['createBy'],
                  createTime : themeWords['createTime'],
                  status : themeWords['status'],
                  arrchildid:themeWords['arrchildid'],
                  arrparentid:themeWords['arrparentid'],
                  themeTableId:themeWords['themeTableId'],
                  themeWordsId:themeWords['themeWordsId'],
                  themeWordsName:tname,
                  parentid:themeWords['parentid'],
                  indexing:true
              };

              tabValList.push(dataArr);
            }
          }
          this.selectedData = tabValList;
          this._keywordTree();//加载主题词列表
        }
        return;
    })
    .catch((err: any)=>{
        return;
    });
  }

  //根据标引主题词和表获取已关联主题词列表
  _getRelThemeList(){

    if(this.currentThemeWordInfo){
      let data = {
        pageNo        : 1,
        pageSize      : 2000,
        queryCriteria : keyword.retrieval.queryCriteria,
        themeTableId  :  this.currentThemeWordInfo['themeTableId'], // 左侧主题词表id
        refThemeTableId  :  this.paramData['themeTableId'], // 当前主题词表id
        themeWordsId  :  this.currentThemeWordInfo['themeWordsId'],    //左侧主题词id
        productId  : this.paramData['productId'],
        taskId  : this.paramData['taskId']
      };
      let url = this.server.baseUrl +  'Service/IdxProduct/getProductThemeRelationList';
      this.request.postRequest(url,data).then((res:any) => {
          if (res.result_code === '0000') {
            let tabValList = [];
            let i=0;
            for (let item of res.result) {
              this.arrTid[i] = item['relThemeWordsId'];
              i++;
          
              let dataArr = {
                  id:item['relThemeWordsId'],
                  label: item['relThemeWordsName'],
                  data: item['relThemeWordsName'],
                  createBy:item['createBy'],
                  createTime : item['createTime'],
                  arrchildid:0,
                  arrparentid:0,
                  themeTableId:item['relThemeTableId'],
                  themeWordsId:item['relThemeWordsId'],
                  themeWordsName:item['relThemeWordsName'],
                  parentid:0,
                  indexing:true
              };

              tabValList.push(dataArr);
              
            }
            this.selectedData = tabValList;
            this._keywordTree();//加载主题词列表
          }else{
              this.hintsService.messages(res.message,res.result_code);
          }
          return;
      })
      .catch((err: any)=>{
          this.hintsService.messages("error","error");
          return;
      });
    }
}

  _processTreeData(list: Array<any>, idName, parentIdName, labelName): Array<any> {
    return this._toTree(list, '0', idName,parentIdName,labelName);
  }

  _toTree(list: Array<any>, topId = '0', idName, parentIdName, labelName) {
    let idKey = idName;
    let result = [];
    
    for (let item of list) {
       
        if (item[parentIdName] == topId) {

          let children = this._toTree(list, item[idKey], idName, parentIdName, labelName)
             if (children && children.length > 0) {
                 item.children = children;
           } 
           //重组主题词名称
           let tname = item['name'];
          if(item['arrparentid'] != '0'){
            tname = this._getThemeName(list,item['arrparentid'])+item['name'];
          }
          
          //是否已经标引
          let isChecked = false;
          if(this.arrTid.length > 0){
            for(let j=0;j < this.arrTid.length;j++)
            {
                if(Number(this.arrTid[j]) == Number(item['themeWordsId'])){
                  isChecked = true;
                }
            }
          }
          let dataArr = {'data':{
              id:item['themeWordsId'],
              arrchildid:item['arrchildid'],
              arrparentid:item['arrparentid'],
              checkStatus:item['checkStatus'],
              createBy:item['createBy'],
              child:item['child'],
              name : item['name'],
              createTime : item['createTime'],
              status : item['status'],
              themeCode:item['themeCode'],
              themeGroupId:item['themeGroupId'],
              themeTableId:item['themeTableId'],
              themeWordsId:item['themeWordsId'],
              parentid:item['parentid'],
              themeWordsName:tname,
              description:item['description'],
              indexing:false,
              isChecked:isChecked
          },'children':children};


          result.push(dataArr);
        }
    }
    return result;
  }

  /**
   * 展开所有树节点
   */
  private _expandAll() {
    this.treeDataScroll.forEach(node => {
      this.expandRecursive(node, true);
    });
  }

  // 递归
  private expandRecursive(node: TreeNode, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.hasOwnProperty('childProductTypeVoList')) {
      node.children = node['childProductTypeVoList'];
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }

  /**
   * 获取主题词的完整路径名称（2）
   */
  _getThemeName(list,arrparentid){
    let tname = '';
    if(list.length > 0){
      if(arrparentid != 0){
        let arrId = arrparentid.split(",");
        if(arrId){
          list.forEach(item => {
            arrId.forEach(tid => {
                if (Number(tid) === Number(item['themeWordsId'])) {
                  tname += item['name']+'\\';
                }
            });
          });
        }
      }
    }
    return tname;
  }

  //搜索
  search() {
    this.pageNo = 1;
    this.previousActive = false;
    this.tableData = {
      token         : 'b25dbd7138cf48e09941087e6d9a2e93',
      themeTableId  : this.paramData['themeTableId'],
      pageNo        : this.pageNo,
      pageSize      : this.pageSize,
      checkStatus   : 1,
      queryCriteria : this.searchData,
    };
    this._infoScroll();
    this._clickButton();
    
  }
  //响应搜索
  changesearch() {
      this.search();
  }
  _infoSearch(){
    this.searchData = '';
  }

   checkNode(str) {
    if(this.selectedData){
      this.selectedData.splice(this.selectedData.findIndex(item => item['id'] === str), 1);
    }
   }

   /**
    * 初始化主题词
    */
   _infoTheme(){
    this.getCheckedTableId = [];
    this.arrTid = [];
   }

   /**
    * 扩展节点
    * @param event 
    */
  onNodeExpand(event) {

    if(this.getCheckedTableId.length > 0){
      this.getCheckedTableId.forEach(str => {
        this.selectedData.splice(this.selectedData.findIndex(item => item['id'] === str['val']), 1);
      });
      this._infoTheme();
    }
  
  }

  /**
   * 折叠节点
   * @param event 
   */
  onNodeCollapse(event){
    this.onNodeExpand(event);
  }

  /**
   * 分页
   * @param pagination 
   */ 
  _pagination(pagination: Array<any>) {
    this.pageNo = pagination[0].pageNumber;
    this.pageSize   = pagination[0].pageSize;
    this.naturalNum = (this.pageNo - 1) * this.pageSize;
    this._clickButton();
  }
}
